package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.base.domain.OrderList;
import cn.wolfcode.trip.base.query.OrderQueryObject;
import cn.wolfcode.trip.base.service.IOrderListService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 登录相关的控制器
 */
@Controller
@RequestMapping("/orderList")
public class OrderListController {
    @Autowired
    private IOrderListService orderListService;

    /**
     * 用户我的订单页面
     * @param qo
     * @return
     */
    @GetMapping
    @ResponseBody
    public Object list(OrderQueryObject qo) {
        qo.setOrderBy("creationtime desc");
        PageInfo query = orderListService.query(qo);
        return query;
    }

    /**
     * 商城积分兑换
     * @param orderList
     * @param request
     * @return
     */
    @PostMapping
    @ResponseBody
    public Object shop(OrderList orderList, HttpServletRequest request) {
        JSONResult jsonResult = new JSONResult();
        try {
            orderListService.save(orderList);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark(e.getMessage());
        }
        return jsonResult;
    }

    /**
     * 购物车批量兑换
     * @param orderList
     * @param request
     * @return
     */
    @PostMapping("/cart")
    @ResponseBody
    public Object shopCar(@RequestBody OrderList[] orderList, HttpServletRequest request) {
        JSONResult result = new JSONResult();
        List<Long> productids =(List<Long>) (request.getSession().getAttribute("SEESION_IN_PRODUCTS"));
        for (OrderList list : orderList) {
            orderListService.save(list);
            //结算后删除session
            if(productids.contains(list.getProduct().getId())){
                productids.remove(list.getProduct().getId());
            }
        }
        request.getSession().setAttribute("SEESION_IN_PRODUCTS",productids);
        return result;
    }
}
